package com.wsc.wscbirthdaykeeper.persistence;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.wsc.wscbirthdaykeeper.R;
import com.wsc.wscbirthdaykeeper.app.KApplication;
import com.wsc.wscbirthdaykeeper.mock.MockData;
import com.wsc.wscbirthdaykeeper.model.entity.Person;
import com.wsc.wscbirthdaykeeper.utils.DialogUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	public static final String DATABASE_NAME = "birthdaykeeper.db";

	private static final int DATABASE_VERSION = 10;

	public DatabaseHelper(Context context) {
		super(context, getDbName(), null, DATABASE_VERSION, R.raw.ormlite_config);
	}

	private static String getDbName() {
		return DATABASE_NAME;
	}

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {

		try {
			TableUtils.createTable(connectionSource, Person.class);
		} catch (SQLException e) {
			DialogUtils.showException(KApplication.getContext(), e);
		}

		try {
			MockData.addData();
		} catch (SQLException e) {
			DialogUtils.showException(KApplication.getContext(), e);
		} catch (Exception e) {
			DialogUtils.showException(KApplication.getContext(), e);
		}

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVer, int newVer) {
		try {
			TableUtils.dropTable(connectionSource, Person.class, true);
			onCreate(db, connectionSource);
		} catch (SQLException e) {
			DialogUtils.showException(KApplication.getContext(), e);
		}
	}
}
